﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace ais_editor
{
    public partial class FormMain : Form
    {
        private DataEditor dataEditor = new DataEditor();
        public FormMain()
        {
            InitializeComponent();
        }

        private void 打开AISToolStripMenuItem_Click(object sender, EventArgs e)
        {

        }

        private void PrintLog(string info)
        {
            this.richTextBox1.SelectionStart = this.richTextBox1.TextLength;
            this.richTextBox1.AppendText(DateTime.Now.ToString("yyyyMMdd hh:mm:ss") + "  " + info + "\n");
            this.richTextBox1.ScrollToCaret(); 
        }
        
        
        public void SaveToCSV(List<Ship> shipList, string filePath)
        {
            //ShipName,CallSign,IMO,MMSI,ShipTypeCN,ShipTypeEN,NavStatusCN,NavStatusEN,Length,Width,
            //Draught,Heading,Course,Speed,Lon,Lat,Rot,Dest,ETA,Receivedtime（UTC+8）,UnixTime,Lon_d,Lat_d,AisType,Dwt
            try
            {
                using (StreamWriter sw = new StreamWriter(filePath))
                {
                    string header = string.Join(",", new string[] {
                        "Id",
                        "Name",
                        "Time",
                        "Lon",
                        "Lat",
                        "Speed",
                        "PLon",
                        "PLat",
                        "LineId",
                        "LineName",
                        "HDistance",
                        "VDistance"
                    });
                    sw.WriteLine(header);
                    foreach (var item in shipList)
                    {
                        //if (item.PLon < 111.131171 || item.Lon > 111.348019)
                        //    continue;
                        sw.WriteLine(item.ToString());
                    }
                }
                MessageBox.Show("数据已成功导出到文件！");
            }
            catch (Exception ex)
            {
                throw;
            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            DateTime dt = DateTime.Now;
            PrintLog("开始读取...");
            dataEditor.LoadFromCSVFile(@"D:\data\船讯网数据样本_长江口一天数据.csv");
            checkedListBox1.Items.AddRange(dataEditor.GetShipNames().ToArray());
            PrintLog("读取数据完毕：" + dataEditor.ShipList.Count);
            PrintLog(string.Join(",", dataEditor.FieldNames));
            PrintLog("Lat：" + dataEditor.ShipList.Min(ele => ele.Lat) + " - " + dataEditor.ShipList.Max(ele => ele.Lat));
            PrintLog("Lon：" + dataEditor.ShipList.Min(ele => ele.Lon) + " - " + dataEditor.ShipList.Max(ele => ele.Lon));
            PrintLog("Time：" + dataEditor.ShipList.Min(ele => ele.Time) + " - " + dataEditor.ShipList.Max(ele => ele.Time));
        }

        private void button4_Click(object sender, EventArgs e)
        {
            //var shipList = listData.Select(ele => new
            //{
            //    lng = ele.Lat,
            //    lon = ele.Lon,
            //    time = ele.Time.Value.Subtract(new DateTime(1970, 1, 1)).TotalSeconds,
            //    dir = new Random().Next(0, 360),
            //    heading = new Random().Next(0, 360),
            //    info = ele.Name,
            //    Name = ele.Name
            //}).GroupBy(ele => ele.Name);

            dataEditor.SaveToJson(dataEditor.ShipList, @"D:\data\tt.json");
        }

        private void button5_Click(object sender, EventArgs e)
        {
            string savePath = @"D:\temp\ais data\";
            string currentPath = @"D:\亿海蓝数据\20250710092329_2021年水科院区域1\";//当前路径
            currentPath = @"D:\亿海蓝数据\20250710092411_2022年水科院区域1\";//当前路径
            currentPath = @"D:\亿海蓝数据\20250710092426_2023年水科院区域1\";//当前路径
            currentPath = @"D:\亿海蓝数据\20250710092446_2024年水科院区域1\";//当前路径
            string[] files = Directory.GetFiles(currentPath);
            int rowIndex = 0;
            foreach (string file in files)
            {
                PrintLog("开始读取..." + file);
                using (System.IO.StreamReader reader = new System.IO.StreamReader(file, Encoding.GetEncoding("GB2312")))
                {
                    string fileName = Path.GetFileName(file);
                    using (StreamWriter sw = new StreamWriter(savePath + fileName))
                    {

                        string header = string.Join(",", new string[] {
                            "ShipName",//0
                            "IMO",//2
                            "MMSI",//3
                            "ShipTypeCN",//4
                            "Length",//8
                            "Width",//9
                            "Heading",//11
                            "Speed",//13
                            "Lon_d",//21
                            "Lat_d",//22
                            "Receivedtime"//19
                        });
                        //ShipName,CallSign,IMO,MMSI,ShipTypeCN,ShipTypeEN,NavStatusCN,NavStatusEN,Length,Width,Draught,Heading,Course,Speed,Lon,Lat,Rot,Dest,ETA,Receivedtime（UTC + 8）,UnixTime,Lon_d,Lat_d,AisType,Dwt
                        sw.WriteLine(header);

                        string headerline = reader.ReadLine();//首行

                        string line = "";
                        while ((line = reader.ReadLine()) != null)
                        {
                            string[] fieldValues = line.Split(',');

                            var lon = Convert.ToDouble(fieldValues[21].Trim());
                            var lat = Convert.ToDouble(fieldValues[22].Trim());

                            Random random = new Random();
                            double randomValue = (random.NextDouble() - 0.5) * 0.001;
                            lon += randomValue;
                            lat += randomValue;
                            string ss = string.Join(",", new string[] {
                                fieldValues[0],
                                fieldValues[2],
                                fieldValues[3],
                                fieldValues[4],
                                fieldValues[8],
                                fieldValues[9],
                                fieldValues[11],
                                fieldValues[13],
                                lon.ToString(),
                                lat.ToString(),
                                fieldValues[19],
                            });
                            if (rowIndex % 15 == 0)
                            {
                                sw.WriteLine(ss.ToString());
                            }

                            rowIndex++;
                        }
                    }    
                }

                //Random rand = new Random();
                //var array = dataEditor.ShipList.OrderBy(x => rand.Next()).ToArray();
                //var newarray = new Ship[array.Length / 10];
                //Array.Copy(array, 0, newarray, 0, newarray.Length);

            }
            PrintLog("处理完成...");
        }

        private void button3_Click(object sender, EventArgs e)
        {

        }
    }
}
